<?php

if(isset($_POST['send'])){

	// Variables
	$recipient = mysql_real_escape_string($_POST['recipient']);
	$sender = $m_user_id;
	$subject = mysql_real_escape_string($_POST['subject']);
	$message_content = mysql_real_escape_string($_POST['message_content']);
	$date = date("F j, Y");
	$time = date("g:i A");
	
	$row = mysql_num_rows(mysql_query("SELECT * FROM messages WHERE sender='$m_user_id'"));
	$fodder = $m_user_id.$date.$time.$row;
	$message_id = make_unique_id($fodder);
	
	$problem = false;
	
	// Check recipient
	if(empty($recipient)){
		$problem = true;
		$content .= '
			<P class="error">Please enter the name of the person you are sending this to.</P>
		';
	}
	
	// Check content
	if(empty($message_content)){
		$problem = true;
		$content .= '
			<P class="error">Please enter your message.</P>
		';
	}
	
	$recipient = trim($recipient);
	
	$query = mysql_query("SELECT user_id FROM users WHERE name='$recipient'");
	$user_exists = mysql_num_rows($query);
	
	// Check if user exists
	if(!empty($recipient) && !$user_exists){
		$problem = true;
		$content .= '
			<P class="error">That user does not exist.</P>
		';
	}
	
	// Change subject if it is empty
	if((empty($subject) || $subject == 'undefined') && !$problem){
		$subject = 'no subject';
	}
	
	$recipient_array = mysql_fetch_assoc($query);
	
	$recipient_id = $recipient_array['user_id'];
	
	if(!$problem){
		mysql_query("INSERT INTO messages VALUES('','$message_id','$sender','$recipient_id','$date','$time','$subject','$message_content','0','0')");
		
		
		
		mysql_close();
		
		refresh(this_page());
		
	}

}
?>